package cn.edu.nsmc.modules.sys.controller;

import cn.edu.nsmc.common.utils.R;
import cn.edu.nsmc.config.Constant;
import cn.edu.nsmc.modules.sys.dao.SysUserDao;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("sys/u")
public class UController extends AbstractController{
    @Autowired
    private SysUserDao sysUserDao;
    @PutMapping("/resetPassword")
    public R resetPassword(Long userId){
        //return sysUserService.resetPassword(userId);
        //校验权限
        //查询更改密码的用户类型
        Integer type=sysUserDao.getUserTypeByUserId(userId);
        if(type==null){return R.error("用户类型异常");}
        Long adminId = getUserId();
        //生成密码
        String salt= RandomStringUtils.randomAlphanumeric(20);
        String newPassword = new Sha256Hash(Constant.DEFAULT_PASSWORD, salt).toHex();
        if (type==1){
            //说明是管理员
            if (adminId==1||adminId==2){
                newPassword = new Sha256Hash(Constant.DEFAULT_PASSWORD_ADMIN, salt).toHex();
                sysUserDao.resetPassword(userId,salt,newPassword);
            }else {
                return R.error("权限不足");
            }
        }else{
            if (sysUserDao.getUserTypeByUserId(adminId)==1){
                if (type==5){
                    newPassword = new Sha256Hash(Constant.DEFAULT_PASSWORD_Repair, salt).toHex();
                }
                sysUserDao.resetPassword(userId,salt,newPassword);
            }else {
                return R.error("权限不足");
            }
        }
        //更新密码
        return R.ok("重置密码成功");
    }
}
